package o.gwtp.editor.client.main;

import o.gwtp.editor.client.navigation.NavigationTabElement;
import o.gwtp.editor.client.navigation.NavigationTabEvent;
import o.gwtp.editor.client.navigation.NavigationTabPresenter;

import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.gwtplatform.mvp.client.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.ContentSlot;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.proxy.Proxy;
import com.gwtplatform.mvp.client.proxy.RevealContentHandler;
import com.gwtplatform.mvp.client.proxy.RevealRootLayoutContentEvent;

/**
 * @author Olivier Monaco
 * @author Christian Goudreau
 */
public class MainPresenter extends
    Presenter<MainPresenter.MyView, MainPresenter.MyProxy> {
  @ProxyStandard
  public interface MyProxy extends Proxy<MainPresenter> {
  }

  public interface MyView extends View {
  }

  @ContentSlot
  public static final Type<RevealContentHandler<?>> CONTENT_SLOT = new Type<RevealContentHandler<?>>();
  public static final Object NAVIGATION_SLOT = new Object();

  private Provider<NavigationTabPresenter> navigation;

  @Inject
  public MainPresenter(EventBus eventBus, MyView view, MyProxy proxy,
      Provider<NavigationTabPresenter> navigation) {
    super(eventBus, view, proxy);
    this.navigation = navigation;
  }

  @Override
  protected void onReveal() {
    super.onReveal();

    setInSlot(NAVIGATION_SLOT, navigation.get());
  }

  @Override
  protected void revealInParent() {
    RevealRootLayoutContentEvent.fire(this, this);
  }

  @Override
  public void setInSlot(Object slot, final PresenterWidget<?> content) {
    super.setInSlot(slot, content);
    if ((slot == CONTENT_SLOT) && (content instanceof NavigationTabElement)) {
      DeferredCommand.addCommand(new Command() {
        @Override
        public void execute() {
          NavigationTabEvent.fireReveal(MainPresenter.this,
              (NavigationTabElement) content);
        }
      });
    }
  }
}
